package com.example.fy.coolweather.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.fy.coolweather.MyApplication;
import com.example.fy.coolweather.R;
import com.example.fy.coolweather.db.CoolWeatherDB;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by fy on 2016/5/11.
 * 启动页面的activity
 */
public class ChooseAreaActivity extends BaseActivity {

    private static final String TAG = "ChooseAreaActivity";
    //地区级别代码
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_DISTRICT = 1;
    public static final int LEVEL_NAME = 2;

    private ListView listView;
    private TextView titleView;
    private ArrayAdapter<String> adapter;
    private CoolWeatherDB coolWeatherDB;
    private List<String> dataList = new ArrayList<>();

    private int currentLevel;//显示当前所选择的地区级别
    private String selectedProvince;
    private String selectedDistrict;
    private String selectedName;

    //是否是从WeatherActivity中跳转过来的
    private boolean isFromWeatherActivity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity",false);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if(prefs.getBoolean("city_selected",false)&&!isFromWeatherActivity){
            Intent intent = new Intent(this,WeatherActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.choose_area);
        /**
         * 将assets里面的weather文件导入到数据库中
         * 因为选择界面的list我找不到相应api，利用其它人的数据库文件weather，文件存放了Area表
         */
        if(!new File(CoolWeatherDB.path).exists()){

            InputStream in;
            try{
                in = getAssets().open("weather");
                coolWeatherDB = CoolWeatherDB.getInstance(this,in);
            }catch (IOException e){
                e.printStackTrace();
            }
        }else{
            coolWeatherDB = CoolWeatherDB.getInstance(this);
        }
        /**
         * 界面
         */
        listView = (ListView)findViewById(R.id.list_view);
        titleView = (TextView)findViewById(R.id.title_text);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(adapter);
        //按照顺序点击，从省开始，市，县。
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if(currentLevel == LEVEL_PROVINCE){
                    selectedProvince = dataList.get(position);
                    queryDistrict();
                }else if(currentLevel == LEVEL_DISTRICT){
                    selectedDistrict = dataList.get(position);
                    queryName();
                }else if(currentLevel == LEVEL_NAME){
                    selectedName = dataList.get(position);
                    Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
                    intent.putExtra("city_name", selectedName);
                    startActivity(intent);
                    finish();
                }
            }
        });
        queryProvinces();
    }

    private void queryProvinces() {
        List<String> temp = coolWeatherDB.loadProvinces();
        //判断数据是否为空，是就重新写入数据到数据库
        if(temp==null){
            InputStream in;
            try {
                in = getAssets().open("weather");
                coolWeatherDB.importToDBFile(in);
                temp =  coolWeatherDB.loadProvinces();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        dataList.clear();
        for(String str:temp){
            dataList.add(str);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        titleView.setText("中国");
        currentLevel = LEVEL_PROVINCE;
    }

    /**
     * 查询地区信息，并添加到listView上
     */
    private void queryDistrict() {
        List<String> temp = coolWeatherDB.loadDistinct(selectedProvince);
        if(temp.size() > 0){
            dataList.clear();
            for(String str:temp){
                dataList.add(str);
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        titleView.setText(selectedProvince);
        currentLevel = LEVEL_DISTRICT;
    }

    /**
     *查询县信息，并显示在listView上
     */
    private void queryName() {
        List<String> temp = coolWeatherDB.loadName(selectedDistrict);
        if(temp.size() > 0){
            dataList.clear();
            for(String str:temp){
                dataList.add(str);
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        titleView.setText(selectedDistrict);
        currentLevel = LEVEL_NAME;
    }

    @Override
    public void onBackPressed() {
        if(currentLevel == LEVEL_NAME){
            queryDistrict();
        }else if(currentLevel == LEVEL_DISTRICT){
            queryProvinces();
        }else{
            if(isFromWeatherActivity){
                Intent intent = new Intent(this,WeatherActivity.class);
                startActivity(intent);
            }
            ActivityControl.finishAll();
        }
    }
}
